import _regeneratorRuntime from "@babel/runtime/regenerator";
import _asyncToGenerator from "@babel/runtime/helpers/esm/asyncToGenerator";
import _classCallCheck from "@babel/runtime/helpers/esm/classCallCheck";
import _createClass from "@babel/runtime/helpers/esm/createClass";
import _inherits from "@babel/runtime/helpers/esm/inherits";
import _createSuper from "@babel/runtime/helpers/esm/createSuper";
import _applyDecoratedDescriptor from "@babel/runtime/helpers/esm/applyDecoratedDescriptor";
import _isNil from "lodash/isNil";

var _dec, _dec2, _class;

/* eslint-disable react/require-default-props */

/**
 * 1. 在组件卸载
 * 2. 使用 如果 配置变化 请重新赋予一个新的key
 * <OnlyOfficeEditor key={JSON.stringify(config)} {...config} />
 * 如果 不基于 cpaas 的服务, 则需要自己定义自己的 OnlyOffice 组件
 * 基于 cpaas 文件 的 onlyOffice 的编辑器
 * OnlyOfficeEditor
 * @date 2019-07-02
 */
import React from 'react';
import { Spin } from 'antd';
import { Bind, Debounce } from 'lodash-decorators';
import request from "../../utils/request";
import intl from "../../utils/intl";
import { getEnvConfig } from "../../utils/iocUtils";
import { getCurrentOrganizationId } from "../../utils/utils";
var OnlyOfficeEditor = (_dec = Debounce(500), _dec2 = Bind(), (_class = /*#__PURE__*/function (_React$PureComponent) {
  _inherits(OnlyOfficeEditor, _React$PureComponent);

  var _super = _createSuper(OnlyOfficeEditor);

  function OnlyOfficeEditor(props) {
    var _this;

    _classCallCheck(this, OnlyOfficeEditor);

    _this = _super.call(this, props);
    _this.state = {
      loaded: false,
      // reloading: false, // 是否 重新加载
      configErrorMessages: null,
      // 如果 configError 不为空, 则显示出错
      saving: false
    };
    _this.iframeRef = React.createRef();
    _this.config = getEnvConfig();
    return _this;
  }

  _createClass(OnlyOfficeEditor, [{
    key: "componentDidMount",
    value: function componentDidMount() {
      this.loadOnlyOfficeData();
    }
    /**
     * 在编辑器卸载之前 需要触发编辑器的 onbeforeunload
     * 通过将 srcdoc 置为空字符串 触发
     */

  }, {
    key: "componentWillUnmount",
    value: function componentWillUnmount() {
      this.triggerDocumentSave();
    }
    /**
     * 通过修改 srcdoc 触发文档的文件保存
     * 500 ms 的延时 让 编辑器有足够的时间来保存内容到内存
     * @param {Function} callback - 保存完毕
     */

  }, {
    key: "triggerDocumentSave",
    value: function () {
      var _triggerDocumentSave = _asyncToGenerator( /*#__PURE__*/_regeneratorRuntime.mark(function _callee(callback) {
        var _this2 = this;

        var saving;
        return _regeneratorRuntime.wrap(function _callee$(_context) {
          while (1) {
            switch (_context.prev = _context.next) {
              case 0:
                saving = this.state.saving;

                if (!saving) {
                  _context.next = 3;
                  break;
                }

                return _context.abrupt("return");

              case 3:
                if (this.iframeRef.current) {
                  this.iframeRef.current.contentDocument.write('');
                  this.setState({
                    saving: true
                  });
                  setTimeout(function () {
                    if (_this2.iframeRef.current) {
                      var srcdoc = _this2.state.srcdoc;

                      _this2.iframeRef.current.contentDocument.write(srcdoc);

                      _this2.setState({
                        saving: false
                      }, function () {
                        callback();
                      });
                    }
                  }, 100);
                }

              case 4:
              case "end":
                return _context.stop();
            }
          }
        }, _callee, this);
      }));

      function triggerDocumentSave(_x) {
        return _triggerDocumentSave.apply(this, arguments);
      }

      return triggerDocumentSave;
    }() // // 不要支持 url 改变
    // componentDidUpdate(prevProps, prevState, snapshot) {
    //   // 比较 影响 编辑的数据是否发生变化
    //   const { organizationId: prevOrganizationId, bucketName: prevBucketName, storageCode: prevStorageCode, permission: prevPermission, url: prevUrl } = prevProps;
    //   const { organizationId, bucketName, storageCode, permission, url } = this.props;
    //   const configProps = { organizationId, bucketName, storageCode, permission, url };
    //   const prevConfigProps = {
    //     organizationId: prevOrganizationId,
    //     bucketName: prevBucketName,
    //     storageCode: prevStorageCode,
    //     permission: prevPermission,
    //     url: prevUrl,
    //   };
    //   if (JSON.stringify(configProps) !== JSON.stringify(prevConfigProps)) {
    //     this.setState({ reloading: true }, () => {
    //       this.loadOnlyOfficeData();
    //     });
    //   }
    // }

  }, {
    key: "loadOnlyOfficeData",
    value: function loadOnlyOfficeData() {
      var _this3 = this;

      if (!this.checkConfigError()) {
        return;
      }

      var _this$props = this.props,
          _this$props$organizat = _this$props.organizationId,
          organizationId = _this$props$organizat === void 0 ? getCurrentOrganizationId() : _this$props$organizat,
          bucketName = _this$props.bucketName,
          storageCode = _this$props.storageCode,
          permission = _this$props.permission,
          url = _this$props.url;
      var CPAAS_FILE = this.config.CPAAS_FILE;
      request("".concat(CPAAS_FILE, "/v1/").concat(organizationId, "/only-office/url"), {
        method: 'POST',
        body: {
          bucketName: bucketName,
          storageCode: storageCode,
          permission: permission,
          url: url
        },
        // 期望返回类型是 文本
        responseType: 'text'
      }).then(function (res) {
        if (typeof res === 'string') {
          // 是文本
          _this3.setState({
            loaded: true,
            // reloading: false,
            srcdoc: res
          }); // this.iframeRef.current.srcdoc=res;


          _this3.iframeRef.current.contentDocument.write(res);
        }
      });
    }
  }, {
    key: "checkConfigError",
    value: function checkConfigError() {
      var _this$props2 = this.props,
          bucketName = _this$props2.bucketName,
          permission = _this$props2.permission,
          url = _this$props2.url;
      var errors = [];

      if (_isNil(bucketName)) {
        errors.push(intl.get('cpaas.common.validation.notNull', {
          name: 'bucketName'
        }));
      }

      if (_isNil(permission)) {
        errors.push(intl.get('cpaas.common.validation.notNull', {
          name: 'permission'
        }));
      }

      if (_isNil(url)) {
        errors.push(intl.get('cpaas.common.validation.notNull', {
          name: 'url'
        }));
      }

      if (errors.length > 0) {
        this.setState({
          configErrorMessages: errors
        });
        return false;
      }

      var configErrors = this.state.configErrors;

      if (configErrors) {
        this.setState({
          configErrorMessages: null
        });
      }

      return true;
    }
  }, {
    key: "render",
    value: function render() {
      var _this$props3 = this.props,
          width = _this$props3.width,
          height = _this$props3.height,
          url = _this$props3.url;
      var _this$state = this.state,
          loaded = _this$state.loaded,
          configErrorMessages = _this$state.configErrorMessages;
      var content;

      if (configErrorMessages !== null) {
        content = /*#__PURE__*/React.createElement("div", {
          style: {
            width: width,
            height: height
          }
        }, /*#__PURE__*/React.createElement("ul", null, configErrorMessages.map(function (errorMessage) {
          return /*#__PURE__*/React.createElement("li", {
            key: errorMessage
          }, errorMessage);
        })));
      } else if (loaded) {
        content = /*#__PURE__*/React.createElement("iframe", {
          ref: this.iframeRef,
          title: url,
          width: width,
          height: height
        });
      } else {
        content = /*#__PURE__*/React.createElement(Spin, {
          width: width,
          height: height,
          spinning: true
        });
      }

      return content;
    }
  }]);

  return OnlyOfficeEditor;
}(React.PureComponent), (_applyDecoratedDescriptor(_class.prototype, "triggerDocumentSave", [_dec, _dec2], Object.getOwnPropertyDescriptor(_class.prototype, "triggerDocumentSave"), _class.prototype)), _class));
export { OnlyOfficeEditor as default };